package core.rdd.transform;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

public class Spark12_WordCount {
    public static void main(String[] args) {
        /**
         *flatMap 是将多集合转换成一个
         */
        // 配置SparkConf指向你的Spark master URL
        SparkConf conf = new SparkConf()
                .setAppName("Spark11_WordCount") // 应用名称
                .setMaster("local[*]"); // 替换成你的master地址
        JavaSparkContext sc = new JavaSparkContext(conf);
        // 创建JavaSparkContext，它是与集群交互的主要入口点
        try {
            JavaRDD<String> rdd = sc.textFile("data/word.txt");

            rdd.collect().forEach(System.out::println);


            JavaRDD<String> stringJavaRDD = rdd.flatMap(new FlatMapFunction<String, String>() {
                @Override
                public Iterator<String> call(String s) throws Exception {
                    Iterator<String> iterator = Arrays.asList(s.split(" ")).iterator();
                    return iterator;
                }
            });

            stringJavaRDD.collect().forEach(System.out::println);


            JavaPairRDD<String, Integer> stringIntegerJavaPairRDD = stringJavaRDD.mapToPair(new PairFunction<String, String, Integer>() {
                @Override
                public Tuple2<String, Integer> call(String s) throws Exception {
                    return new Tuple2<>(s, 1);
                }
            });

            JavaPairRDD<Object, Iterable<String>> objectIterableJavaPairRDD = stringJavaRDD.groupBy(new Function<String, Object>() {
                @Override
                public Object call(String v1) throws Exception {
                    return v1;
                }
            });


            JavaPairRDD<Object, Object> objectObjectJavaPairRDD = objectIterableJavaPairRDD.mapValues(new Function<Iterable<String>, Object>() {
                @Override
                public Object call(Iterable<String> v1) throws Exception {
                    int i=0;
                     for (String s:v1){
                         i++;
                     }

                    return i;
                }
            });
            objectObjectJavaPairRDD.collect().forEach(System.out::println);
            System.out.println("-------------------------------------------------------------------------------------");
            Map<String, Long> stringLongMap = stringIntegerJavaPairRDD.countByKey();

            System.out.println(stringLongMap);


        } finally {
            sc.close();
        }
    }
}
